import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { getMyselfVideo, getMyGood, getMyStar, getOtherGood, getOtherStar, getOtherVideo } from '@/api/video/video.js'
import { MYURL } from '@/utils/express/express.js'
import { io } from 'socket.io-client';
import { getChatNum } from '@/api/chat/chat.js'
export const userStore = defineStore('user', () => {
  const token = ref(null)
  let socket = ref(null)
  const initChatNMum = ref()
  watch(token, () => {
    if (!token.value) return
    socket.value = io(MYURL, {
      auth: (cb) => {
        cb({
          token: token.value.slice(7)
        })
      }
    })
    getChatNum(token.value).then((res) => {
      initChatNMum.value = res.data.message
    })
    socket.value.on('chat-num', (data) => {
      initChatNMum.value = data 
    })
  },
    { immediate: true })
  const FriendState = ref(true)
  const VideoList = ref([])
  const StartList = ref([])
  const GoodList = ref([])
  const TwoVideoList = ref([])
  const TwoStartList = ref([])
  const TwoGoodList = ref([])
  const IsMyself = ref(true)
  function clear() {
    VideoList.value = []
    GoodList.value = []
    StartList.value = []
    TwoVideoList.value = []
    TwoStartList.value = []
    TwoGoodList.value = []
  }
  function getMyVideo() {
    clear()
    IsMyself.value = true
    getMyselfVideo().then((res) => {
      if (res.data.status === 0) {
        VideoList.value = res.data.message
        TwoVideoList.value = res.data.message.slice(0, 2)
      }
    })
    getMyStar().then((res) => {
      if (res.data.status === 0) {
        StartList.value = res.data.message
        TwoStartList.value = res.data.message.slice(0, 2)
      }
    })
    getMyGood().then((res) => {
      if (res.data.status === 0) {
        GoodList.value = res.data.message
        TwoGoodList.value = res.data.message.slice(0, 2)
      }
    })
  }
  function getOtherVideos(up) {
    clear()
    IsMyself.value = false
    getOtherVideo(up).then((res) => {
      if (res.data.status === 0) {
        VideoList.value = res.data.message
        TwoVideoList.value = res.data.message.slice(0, 2)
      }
    })
    getOtherStar(up).then((res) => {
      if (res.data.status === 0) {
        StartList.value = res.data.message
        TwoStartList.value = res.data.message.slice(0, 2)
      }
    })
    getOtherGood(up).then((res) => {
      if (res.data.status === 0) {
        GoodList.value = res.data.message
        TwoGoodList.value = res.data.message.slice(0, 2)
      }
    })
  }
  function changeFriendState(e) {
    FriendState.value = e
  }
  function change_token(e) {
    token.value = e
  }
  return { token, socket, change_token, initChatNMum, FriendState, changeFriendState, VideoList, StartList, GoodList, getMyVideo, TwoVideoList, TwoGoodList, TwoStartList, getOtherVideos, IsMyself }
}, {
  persist: {
    key: 'token',
    paths: ['token']
  }
})
